<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="公司">
              <a-cascader
                v-model="pageData.companyId"
                :options="pageData.nameList"
                allow-clear
                class="bacClass"
                popup-container="html"
              />
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading"
                                v-model="pageData.dropDownData" :filter-option="false" allow-clear
                                @focus="foucusUseFrim">
                                <a-option v-for="item in pageData.nameList" :value="item['id']">
                                    {{ item['typeName'] }}{{ item['typeName'] == "" ? "" : "-" }}{{ item['typeName'] }}
                                </a-option>
                            </a-select> -->
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar :items="pageData.btnList" @select="selectHandler"> </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                <a-tab-pane> -->
      <!--
                        表格插件
                    -->
                    <div class="w-full h-full">
                      <encapsulation-agrid style="height: 100%" ref="gridOption" :configaggrid="configTable"></encapsulation-agrid>
                    </div>
      <!-- <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" 
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
      ></AgGridVuesCopys> -->
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>
    <!-- <paginationCopys
      :page-size-options="optionsList"
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="size"
      :current="page"
    /> -->
    <!-- <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="80px" label="公司" field="companyId"
                        :rules="[{ validator: isChiese }, { required: true, message: '公司必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-cascader v-model="dataForm.companyId" :options="pageData.firmList" allow-clear ref="casOb"
                            @change="cascaderChange" class="bacClass" 
                            :title="pageData.title"   />
                      
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="岗位名称" field="post"
                        :rules="[{ required: true, message: '岗位名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" v-model="dataForm.post" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="备注" field="remark">
                        <a-textarea class="bacClass"  placeholder="" v-model="dataForm.remark"
                             :max-length="400" allow-clear show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer> -->
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
// 引入

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'


interface PositionList {
  // "id": any,
  // "post": string | undefined,
  // "companyId": string | undefined,
  // "firmName": string | undefined,
  // "remark": string | undefined,
  // "createName": string | undefined,
  // "createTime": string | undefined,
  // "updateName": string | undefined,
  // "updateTime": string | undefined,
  companyCode: any
  code: any
  is_active: any
  company_id: any
  companyName: any
  positionCode: any
  remark: any
  sort_index: any
  update_date: any
  positionName: any
  update_user: any
  post: any
  post_type_id: any
  id: any
  create_user: any
  create_date: any
  position_id: any
}

export default {
  name: 'PositionList',

  setup() {
    const optionsList: any = ref(pagingList)
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)

    function doRefresh() {
      try {
        gridOption.value.setQuery({
          deleteState: 0,
          company_id: pageData.companyId,
      })
      } catch (error) {
        console.log(error);
      }
      // pageData.pageLoading = true
      // post({
      //   url: 'org/baPost/getPage',
      //   data: {
      //     page: page.value,
      //     size: size.value,
      //     deleteState: 0,
      //     company_id: pageData.companyId,
      //   },
      // })
      //   .then(({ data, code }: any) => {
      //     if (code === 200) {
      //       table.handleSuccess(data.list)
      //       // 查询方法改
      //       gridOption.value.setRowData(data.list)
      //       total.value = data.total
      //     }
      //   })
      //   .catch(console.log)
      //   .finally(() => {
      //     pageData.pageLoading = false
      //   })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '岗位',
        key: 'post',
        dataIndex: 'post',
        width: 200,
      },
      {
        title: '工号',
        key: 'code',
        dataIndex: 'code',
        width: 150,
      },

      {
        title: '公司编号',
        key: 'companyCode',
        dataIndex: 'companyCode',
        width: 150,
      },

      {
        title: '公司',
        key: 'companyName',
        dataIndex: 'companyName',
        width: 150,
      },
      {
        title: '职务编号',
        key: 'positionCode',
        dataIndex: 'positionCode',
        width: 150,
      },
      {
        title: '职务名称',
        key: 'positionName',
        dataIndex: 'positionName',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 200,
      },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
        width: 200,
      }
      // if (o.slotName === 'act') {
      //     obj['resizable'] = false
      //     obj['filter'] = false
      //     obj['sortable'] = false
      //     obj["lockPosition"] = "right"
      //     obj["width"] = 80
      //     obj['cellRenderer'] = {
      //         template: `<a-tag color="#ff7d00" class="gesture" @click="a">修改</a-tag>`,
      //         setup(props: any) {
      //             const a = () => {
      //                 editHandler(props.params.data)
      //             }
      //             return {
      //                 a
      //             }
      //         }

      //     }
      // }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    let configTable = ref({
      url: 'org/baPost/getPage', //接口路径
      queryData: {
        //接口参数
      },
      // isGet:true,//是否是get请求
      // isLimit:true,//后端分页接收limit而非size
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: false, //点击行是否多选
      column: tc,
      fileName: 'positionList'
    })
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      firmList: any[]
      title: any
      companyId: any
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增岗位列表',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      firmList: [],
      title: '',
      companyId: null,
    })
    onMounted(() => {
      emitter.on("refresh-PositionList", () => doRefresh());
      getFrimList()
    })
    let cxbl: any = undefined
    //查询
    const selectHandler = () => {
      page.value = 1
      if (pageData.dropDownData == '') {
        cxbl = undefined
      } else {
        cxbl = pageData.dropDownData
      }
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    // const addHandler = () => {
    //     for (var key in dataForm) {
    //         if (key === "id") {
    //             dataForm[key] = null;
    //         } else {
    //             dataForm[key] = "";
    //         }
    //     }

    //     pageData.showAdd = true
    //     pageData.sideTitle = '新增岗位列表'

    // }
    // const dataForm = reactive<PositionList>({
    //     "id": null,
    //     "remark": "",
    //     "post": "",
    //     "companyId": "",
    //     "firmName": "",
    //     "createName": "",
    //     "createTime": "",
    //     "updateName": "",
    //     "updateTime": "",

    // })

    // 表格准备事件
    const gridOption = ref()
    // const gridReady = (params: any) => {
    //   gridOption.value = params.api
    // }

    let formRef = ref<FormInstance>()
    // const sideOk = () => {
    //     formRef.value?.validate().then((err) => {
    //         if (!err) {
    //             formRef.value?.validate().then((err) => {
    //                 if (!err) {
    //                     pageData.pageLoading = true;

    //                     dataForm['firmName'] = undefined

    //                     if (pageData.sideTitle === "新增岗位列表") {
    //                         post({
    //                             url: "org/post/insert",
    //                             data: dataForm,
    //                         }).then((res: any) => {
    //                             if (res.code === 200) {
    //                                 formRef.value?.resetFields();
    //                                 pageData.showAdd = false;

    //                                 Message.success({
    //                                     content: "新增成功",
    //                                     duration: 5000,
    //                                 });
    //                             } else {
    //                                 Message.error({
    //                                     content: res.message,
    //                                     duration: 5000,
    //                                 });
    //                             }
    //                             doRefresh();
    //                         }).finally(() => {
    //                             doRefresh();
    //                             pageData.pageLoading = false
    //                         })
    //                     } else {
    //                         post({
    //                             url: "org/post/update",
    //                             data: dataForm,
    //                         }).then((res: any) => {
    //                             if (res.code === 200) {
    //                                 formRef.value?.resetFields();
    //                                 pageData.showAdd = false;
    //                                 Message.success({
    //                                     content: "修改成功",
    //                                     duration: 5000,
    //                                 });

    //                             } else {
    //                                 Message.error({
    //                                     content: res.message,
    //                                     duration: 5000,
    //                                 });
    //                             }

    //                         }).finally(() => {

    //                             doRefresh();
    //                             pageData.pageLoading = false
    //                         })
    //                     }
    //                 }
    //             });
    //         }

    //     })
    // }
    // const deleteHandler = () => {
    //     if (gridOption.value.getSelectedRows().length === 0) {
    //         Message.error({
    //             content: '请勾选数据',
    //             duration: 5000
    //         })
    //         return
    //     }

    //     Modal.confirm({
    //         title: '系统提示',
    //         content: '确认删除选中的数据?',
    //         onOk() {
    //             pageData.pageLoading = true;
    //             post({
    //                 url: 'org/post/deleteList',
    //                 data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
    //             }).then(({ code, data }: any) => {
    //                 if (code === 200) {
    //                     Message.success({
    //                         content: '删除成功',
    //                         duration: 5000
    //                     })
    //                     pagination.page = 1
    //                     doRefresh()

    //                 } else {
    //                     Message.error({
    //                         content: '删除失败',
    //                         duration: 5000
    //                     })
    //                 }

    //             }).finally(() => {
    //                 pageData.pageLoading = false
    //             });
    //         }
    //     })
    // }

    // let curobj = null
    // const editHandler = (record: PositionList) => {
    //     curobj = record
    //     for (let key in record) {
    //         dataForm[key] = record[key]
    //     }
    //     pageData.sideTitle = '修改岗位列表'
    //     pageData.showAdd = true
    // }
    //判断是否填写了中文

    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    //拿到所有公司

    function getFrimList() {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
        data: {},
      }).then((result: any) => {
        if (result.code === 200) {
          pageData.firmList = result.data
          pageData.nameList = result.data
        } else {
          Message.error(result.message)
        }
      })
    }
    const casOb = ref()
    //公司改变
    const cascaderChange = () => {
      //拿到选中的这个节点数组
      setTimeout(function () {
        pageData.title = slicing(casOb.value.selectViewValue[0]['label'])
      }, 500)
    }
    const localeText1: any = ref(localeText)
       //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('gwlb.cx')) {

            pageData.btnList.push("查询")
        }
      
    return {
      casOb,
      optionsList,
      cascaderChange,
      localeText1,
      getFrimList,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      // editHandler,
      // deleteHandler,
      // sideOk,
      formRef,
      // dataForm,
      // addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      headerShow,
      handleChange,
      // gridReady,
      configTable,
      gridOption
    }
  },
  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>